<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>将数组关系转换成树关系</title>
  </head>
</html>

<script>
  function arrToTree(arr) {
    if (!Array.isArray(arr)) throw new Error("传入参数不是数组");
    const newObj = [];
    const aTOb = {};
    arr.forEach((element) => {
      aTOb[element["id"]] = element;
    });

    arr.forEach((element) => {
      if (aTOb[element["pid"]]) {
        (
          aTOb[element["pid"]].children || (aTOb[element["pid"]].children = [])
        ).push(element);
      } else {
        newObj.push(element);
      }
    });
    return newObj;
  }
  const obj = [
    { pid: -1, id: 0, name: "z" },
    { pid: 0, id: 1, name: "zz" },
    { pid: 1, id: 2, name: "zzz" },
    { pid: 1, id: 3, name: "zzzz" },
  ];
  console.log(JSON.stringify(arrToTree(obj)));
</script>
